package com.clouddot.baipai.ui.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.model.beam.getArcticById.getArcticByIdResponse;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import static com.clouddot.baipai.ui.activity.H_SMainActivity.MSG_ONE;

/**
 * Created by wxy on 2018/5/10.
 */

public class A_UrgentAdapter extends PagerAdapter {

    public static final int MAX_SCROLL_VALUE = 10000;

    private List<getArcticByIdResponse> mItems;
    private Context mContext;
    private LayoutInflater mInflater;
    public A_UrgentAdapter(List<getArcticByIdResponse> items, Context context) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        mItems = items;
    }

    /**
     * @param container
     * @param position
     * @return 对position进行求模操作
     * 因为当用户向左滑时position可能出现负值，所以必须进行处理
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        //对ViewPager页号求摸取出View列表中要显示的项
        position %= mItems.size();
        Log.d("Adapter", "instantiateItem: position: " + position);
        getArcticByIdResponse response = mItems.get(position);

        final hander hander = new hander();
        hander.title.setText(response.BaseData.getTitle());
        hander.time.setText(response.BaseData.getCreateTimeText());
        final String html = EscapeUnescapeUtil.unescape(response.BaseData.getDetail());
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                hander.spanned = Html.fromHtml(html, new Html.ImageGetter() {
                    @Override
                    public Drawable getDrawable(String source) {
                        String s =  source.contains("http") ? source: Env.getAppContext().IP + source;
                        InputStream is = null;
                        try {
                            is = (InputStream) new URL(s).getContent();
                            Drawable d = Drawable.createFromStream(is, null);
                            d.setBounds(0, 0, d.getIntrinsicWidth(),
                                    d.getIntrinsicHeight());
                            is.close();
                            return d;
                        } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                }, null);
                Message msg = new Message();
                msg.what = 2;
                msg.obj = hander;
                mhandler.sendMessage(msg);

            }
        });

        //如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
        ViewParent viewParent = hander.ret.getParent();
        if (viewParent != null) {
            ViewGroup parent = (ViewGroup) viewParent;
            parent.removeView(hander.ret);
        }
        container.addView(hander.ret);
        return hander.ret;
    }


    /**
     * 由于我们在instantiateItem()方法中已经处理了remove的逻辑，
     * 因此这里并不需要处理。实际上，实验表明这里如果加上了remove的调用，
     * 则会出现ViewPager的内容为空的情况。
     *
     * @param container
     * @param position
     * @param object
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //警告:不要在这里调用removeView, 已经在instantiateItem中处理了
    }


    @Override
    public int getCount() {
        int ret = 0;
        if (mItems.size() > 0) {
            ret = mItems.size();
        }
        return ret;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == (View) object;
    }


    private class hander{
        private View ret = null;
        TextView title;
        TextView time;
        TextView content ;
        Spanned spanned;
        public hander() {
            if(Environment.getInstance().Height <= 100){
                ret = LayoutInflater.from(mContext).inflate(R.layout.h_a_urgentcontent, null);
            }else {
                ret = LayoutInflater.from(mContext).inflate(R.layout.v_a_urgentcontent, null);
            }

             title = ret.findViewById(R.id.title);
             time = ret.findViewById(R.id.time);
             content = ret.findViewById(R.id.content);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case  2:
                    hander hander = (A_UrgentAdapter.hander) msg.obj;
                    hander.content.setText(hander.spanned);
                    break;
            }
        }
    };

}